<template>
	<div class="content-box">
		<el-row :gutter="10" class="head-row">
			<el-col :span="20" class="firstcol">
				<el-button disabled style="margin-right: 0.625rem;" type="text">根据日期筛选数据</el-button>
				<el-date-picker v-model="startDate" type="date" placeholder="开始日期" style="margin-right: 0.625rem;"
					clearable @change="changeStart">
				</el-date-picker>
				<el-date-picker v-model="endDate" type="date" placeholder="结束日期" clearable
					style="margin-right: 0.625rem;" @change="changeEnd">
				</el-date-picker>
			</el-col>
		</el-row>


		<div class="ceshibox">

			<p>
				<vxe-radio-group v-model="selectTab" @change="changeTab">
					<vxe-radio-button v-for="item in tableData.filter((res) => { return !res.is_materials })"
						:label="item.id" :content="item.name" :key="item.id"></vxe-radio-button>
					<vxe-radio-button v-for="item in tableData.filter((res) => { return res.is_materials })"
						:label="item.id" :content="item.name" :key="item.id"></vxe-radio-button>
				</vxe-radio-group>
			</p>

			<div v-if="tableData.filter((res) => { return res.id == selectTab }).length">
				<!-- <div>{{tableData.filter((res) => { return res.id == selectTab })}}</div> -->
				<div v-for="item in tableData.filter((res) => { return !res.is_materials })"
					v-show="selectTab === item.id" :key="item.id">
					<div class="btnGroup">
						<el-button @click="handleDao" type="success">导出excel</el-button>
						<el-button @click="getData" type="primary">刷新数据</el-button>
					</div>
					<vxe-table resizable show-overflow ref="xTree" keep-source :sync-resize="selectTab"
						@cell-click="cellClickEvent" @edit-closed="kkk" :height="totalHeight"
						:tree-config="{ children: 'children', showIcon: 'true', expandAll: 'true', reserve: true }"
						highlight-current-row
						:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }"
						:data="tableData1(item.id)">
						<vxe-table-column type="seq" width="60"></vxe-table-column>
						<vxe-table-column field="name" title="类目" tree-node width="200">
						</vxe-table-column>
						<vxe-table-column v-for="(item, index) in placelist" :title="item.name"
							:field="'maindata[' + index + '].money'" :edit-render="{ name: 'input' }" :key="item.id">
						</vxe-table-column>
						<vxe-table-column title="预算、测算总金额" field="predict_money">
						</vxe-table-column>
						<vxe-table-column title="动态累计发生金额" type="number" field="total_money">
							<template v-slot="{ row }">
								<span>{{ totalmoney(row) }} 元</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="剩余金额" field="over_money">
							<template v-slot="{ row }">
								<span>{{ leaveAmount(row) }} 元</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="备注" field="remarks.remark" :edit-render="{}">
							<template #edit="{ row }">
								<vxe-input v-model="row.remarks.remark" type="text" @blur="changeRemark(row.remarks)">
								</vxe-input>
							</template>
						</vxe-table-column>
					</vxe-table>

				</div>

			</div>
			<div v-else style="text-align:center;font-size:7vh;color:gray">该时段数据为空</div>

			<div v-if="tableData.filter((res) => { return res.id == selectTab }).length"></div>
			<div v-for="item in  tableData.filter((res) => { return res.is_materials })" v-show="selectTab === item.id"
				:key="item.id">
				<div v-if="tableData.filter((res) => { return res.id == selectTab }).length">
					<div class="btnGroup">
						<el-button @click="handleDaos" type="success">导出excel</el-button>
						<el-button @click="getData" type="primary">刷新数据</el-button>

					</div>

					<vxe-table resizable show-overflow ref="xTree2" keep-source :sync-resize="selectTab"
						@cell-click="cellClickEvent" @edit-closed="kkk" highlight-current-row
						:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }"
						:tree-config="{ children: 'children', showIcon: 'true', expandAll: 'true', reserve: true }"
						:data="tableData1(item.id)" :height="totalHeight">

						<vxe-table-column type="seq" width="60"></vxe-table-column>
						<vxe-table-column field="name" title="类目" tree-node width="200">


						</vxe-table-column>

						<vxe-table-colgroup v-for="(item, index) in placelist" :title="item.name" :key="index">
							<vxe-table-column title="单价" :field="'maindata[' + index + '].money'"
								:edit-render="{ name: 'input' }" width="100">
							</vxe-table-column>
							<vxe-table-column title="数量" :field="'maindata[' + index + '].num'"
								:edit-render="{ name: 'input' }" width="100">
							</vxe-table-column>
						</vxe-table-colgroup>
						<vxe-table-column title="预算、测算总金额" field="predict_money" width="200">
						</vxe-table-column>
						<vxe-table-column title="预算、测算总工程量" field="predict_do" width="200">
						</vxe-table-column>
						<vxe-table-column title="动态累计发生工程量汇总" field="total_do" width="200">
							<template v-slot="{ row }">
								<span>{{ totalnum(row) }}</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="动态累计发生金额" type="number" field="total_money" width="200">

							<template v-slot="{ row }">
								<span>{{ totalmoney(row) }} 元</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="剩余工程量" field="over_do" width="200">
							<template v-slot="{ row }">
								<span>{{ leaveNum(row) }}</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="剩余金额" field="over_money" width="200">
							<template v-slot="{ row }">
								<span>{{ leaveAmount(row) }} 元</span>
							</template>
						</vxe-table-column>
						<vxe-table-column title="备注" field="remarks.remark" :edit-render="{}" width="200">

							<template #edit="{ row }">
								<vxe-input v-model="row.remarks.remark" type="text" @blur="changeRemark(row.remarks)">
								</vxe-input>
							</template>
						</vxe-table-column>
					</vxe-table>

				</div>
				<div v-else style="text-align:center;font-size:7vh;color:gray">该时段数据为空</div>
			</div>
		</div>
	</div>
</template>

<script>
import {
	getArticalData,
	UpdateArticalData,
	UpdateRemarkData,
} from "../../api/article";

const XEUtils = require('xe-utils')
export default {
	name: "VueElementAdminIndex",
	data() {
		return {
			pickerOptions0: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() < this.startDate
					}
				}
			},
			end_Date: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() <= this.startDate
					}
				}
			},
			showheader: "false",
			smallActive: "tujian",
			tabPosition: "top",
			keyword: "",
			moduleslist: [],
			keyword: "",
			tableData: [],
			// tableDataC: [],
			placelist: [],
			pid: 15,
			selectTab: '',
			isShow: false,
			startDate: '',
			endDate: '',
			currentDate: new Date(),
			rowData: [],
			nameDisabled: false,
			upData: [],		//旧的数据，用于比较新旧数据，避免不必要的请求。	
			// startDate:"",
			// endDate:"",
			timeMan: "",
			totalSquare: 0,
			totalHeight: 520
		};
	},
	created() {
		// this.startDate = this.$route.query.createTime
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
		this.startDate = this.dealTime(new Date())
		this.endDate = this.startDate
		this.getData();

	},
	mounted() {
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
		window.addEventListener("resize", () => {
			// console.log(window.innerWidth)
			this.totalHeight = 520 * window.innerWidth / 1536
			console.log(this.totalHeight)
		})
	},
	methods: {
		//修改备注
		async changeRemark(res) {
			await UpdateRemarkData(res)
		},
		//禁止编辑
		activeCellMethod({ row, rowIndex }) {
			console.log('Bianji', row);
			this.upData = []
			row.maindata.forEach((res) => {
				this.upData.push({ ...res })
			})
			// if (row.level == 1) {
			if (row.children !== undefined || !row.id) {
				this.$XModal.message({
					message: '禁止编辑',
					status: 'error'
				})
				return false
			}

			if (this.startDate != this.endDate || this.startDate > this.dealTime(this.currentDate)) {
				console.log(this.startDate, this.dealTime(this.currentDate))
				this.$XModal.message({
					message: '禁止编辑，确保表单时间范围为一天',
					status: 'error'
				})
				return false
			}
			// if (row.level == 2 && row.children !== undefined) {
			// 	return false
			// }
			return true
		},
		// //数据合并
		countAmount(row) {
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveAmount(row) {
			// let newresult = Number(row.predict_money) - Number(this.countAmount(row))
			let newresult = Number(row.totalmoney)
			return newresult.toFixed(2)
		},

		//材料表相关
		totalnum(row) {
			if (row.name == "总计单方造价（指标）") {
				return XEUtils.sum(row.maindata, 'num')
			}
			return XEUtils.sum(row.maindata, 'num')
		},
		totalmoney(row) {
			if (row.name == "总计单方造价（指标）") {
				return XEUtils.sum(row.maindata, 'money')
			}
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveNum(row) {
			// let newresult = Number(row.predict_do) - Number(this.totalnum(row))
			let newresult = Number(row.totalnum)
			return newresult
		},
		//获取当日数据
		getCurrentData() {
			this.getData()
		},
		//点击单元格触发@cell-click="cellDown"
		cellClickEvent(row) {
			this.rowData = row.row.maindata
		},
		//单元格失去焦点时修改
		async kkk(row, rowIndex) {
			const arr = this.rowData
			let list = row.row.maindata
			var objNum = {}
			var isExist = false;
			for (var i = 0; i < list.length; i++) {
				var obj = list[i];
				var money = obj.money;
				var num = obj.num;
				// var isExist = false;
				for (var j = 0; j < this.upData.length; j++) {
					if (this.upData[i].money != money || this.upData[i].num != num) {
						const res = await UpdateArticalData(obj)
						if (res.code === 200) {
							isExist = true
						} else {
							this.$XModal.message({
								message: res.message,
								status: 'error'
							})
							return false
						}
					}
					// var aj = arr[j];
					// var n = aj.money;
					// if (n == money) {
					// 	isExist = true; 
					// 	break;
					// }
					// objNum = obj
				}
			}
			if (isExist) {
				window.clearTimeout(this.timeMan)
				this.timeMan = window.setTimeout(() => {
					this.getData()
				}, 30000)		//三十秒后自动刷新

			}
			// console.log(list);
			// const res = await UpdateArticalData(objNum)
			// if (res.code === 200) {
			// 	return this.$message.success('修改成功')
			// }
		},
		//初始获取数据
		async getData() {
			// if(this.endDate ==''){
			// 	const res = await getArticalData({
			// 		project_id: this.pid,
			// 		day_id:currentDate
			// 	});
			// }
			const res = await getArticalData({
				project_id: this.pid,
				start_day: this.startDate,
				end_day: this.endDate,
				day_id: '',

			});

			console.log(res);

			var templist = res.moduleslist
			this.gettotal = (aimlist) => {
				aimlist.map((res5) => {
					res5.totalnum = Number(res5.predict_do) - Number(res5.totalnum)
					res5.totalmoney = Number(res5.predict_money) - Number(res5.totalmoney)
					if (res5.children) {
						this.gettotal(res5.children)
					}
				})
			}
			this.gettotal(templist)

			this.tableData = templist
			this.tableDataa = JSON.parse(JSON.stringify(templist))
			//
			this.moduleslist = res.moduleslist
			this.placelist = res.placelist
			if (res.moduleslist.length && !this.selectTab) {
				this.selectTab = res.moduleslist[0].id
			}
			if (this.$refs.xTree) {
				this.$refs.xTree.forEach((res) => {
					this.$nextTick(() =>
						res.setAllTreeExpand(true)
					)
				})
			}
			if (this.$refs.xTree2) {
				this.$refs.xTree2.forEach((res) => {
					this.$nextTick(() =>
						res.setAllTreeExpand(true)
					)
				})
			}
		},

		changeTab() {
			this.$refs.xTree.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
			this.$refs.xTree2.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
		},

		//将date类型的数据处理成yyyy-mm-dd类型的数据
		dealTime(res) {
			var dateList = {
				y: res.getFullYear(),
				M: res.getMonth() + 1,
				d: res.getDate(),
			}
			if (String(dateList["M"]).length == 1) {
				dateList["M"] = '0' + dateList["M"]
			}
			if (String(dateList["d"]).length == 1) {
				dateList["d"] = '0' + dateList["d"]
			}
			return dateList["y"] + "-" + dateList["M"] + "-" + dateList["d"]
		},

		changeStart(res) {
			if (!res) {
				this.startDate = ""
				this.getData()
				return false
			}
			this.startDate = this.dealTime(res)
			this.getData()
		},
		changeEnd(res) {
			if (!res) {
				this.endDate = ""
				this.getData()
				return false
			}
			this.endDate = this.dealTime(res)
			this.getData()
		},


		handleDao() {
			this.$refs.xTree[0].exportData({
				filename: "字段",
				type: "xlsx",
				useStyle: true,
				data: this.exportData
			})
		},

		handleDaos() {
			this.$refs.xTree2[0].exportData({
				filename: "字段",
				type: "xlsx",
				useStyle: true,
				data: this.exportData
			})
		},

		seqMethod({ row, rowIndex }) {
			if (!row.id) {
				return "#"
			} else {
				return rowIndex
			}
		},

	},
	computed: {
		//生成包括统计结果的数据
		tableData1() {
			return function (aimid) {

				var resItem = this.tableData.filter((res) => { return res.id == aimid })

				var temp = []
				var total_predict_do = 0
				var total_predict_money = 0
				var total_over_do = 0
				var total_over_money = 0
				var total_money = 0
				var total_money2 = 0
				var total_num = 0
				var total_num2 = 0
				var totalSquare = 0
				this.placelist.forEach((res) => {
					if (res.square) {
						totalSquare += (res.square)
					}
				})
				resItem.forEach((item, index) => {

					if (item.predict_do) {
						total_predict_do += item.predict_do
					}
					if (item.predict_money) {
						total_predict_money += item.predict_money
					}
					if (item.over_do) {
						total_over_do = item.over_do
					}
					if (item.over_money) {
						total_over_money = item.over_money
					}
					if (!index) {
						temp = item.maindata
					} else {
						for (var i = 0; i < temp.length; i++) {
							if (item.maindata[i].money) {
								// total_money += item.maindata[i].money
								// total_money2 += item.maindata[i].money / res.placelist[i].square
								if (item.maindata[i].num) {
									total_num += item.maindata[i].num
									total_num2 += item.maindata[i].num / res.placelist[i].square
									temp[i].money = Number(temp[i].money) + Number(item.maindata[i].num) * Number(item.maindata[i].money)
								} else {
									temp[i].money = Number(temp[i].money) + Number(item.maindata[i].money)
								}
							}

						}
					}
				})
				var tempa = JSON.parse(JSON.stringify(temp))        //总造价指标
				this.placelist.forEach((res, index) => {
					tempa[index].money = (temp[index].money / Number(res.square)).toFixed(2)
					if (tempa[index].num) {
						tempa[index].num = (temp[index].num / Number(res.square)).toFixed(2)
					}
				})
				var restemp = []
				this.moduleslista = ["总计造价", "总计单方造价（指标）"]
				this.moduleslist = [...this.moduleslista, "总计造价", "总计单方造价（指标）"]

				total_predict_do = total_predict_do.toFixed(2)
				total_predict_money = total_predict_money.toFixed(2)
				total_over_do = total_over_do.toFixed(2)
				total_over_money = total_over_money
				total_money = total_money.toFixed(2)
				total_money2 = total_money2.toFixed(2)
				total_num = total_num.toFixed(2)
				total_num2 = total_num2.toFixed(2)
				totalSquare = totalSquare.toFixed(2)


				for (var i = 0; i < 2; i++) {
					if (i == 0) {
						restemp.push({ name: this.moduleslista[i], maindata: temp, predict_do: total_predict_do, predict_money: total_predict_money, over_do: total_over_do, over_money: total_over_money, total_num, total_money, totalmoney: total_over_money, totalnum: total_over_do })
					} else {
						restemp.push({ name: this.moduleslista[i], maindata: tempa, predict_do: (total_predict_do / totalSquare).toFixed(2), predict_money: (total_predict_money / totalSquare).toFixed(2), total_num: total_num2, total_money: total_money2, totalmoney: (total_over_money / totalSquare).toFixed(2), totalnum: (total_over_do / totalSquare).toFixed(2) })
					}
				}
				// console.log([...resItem,...restemp])

				var temp = [...resItem, ...restemp]
				var showDetail = (totalList) => {
					totalList.map((item) => {
						item["count_Amount"] = this.countAmount(item)
						item["over_money"] = this.leaveAmount(item)
						item["total_do"] = this.totalnum(item)
						item["total_money"] = this.totalmoney(item)
						item["over_do"] = this.leaveNum(item)
						if (item.children) {
							showDetail(item.children)
						}
					})
				}
				showDetail(temp)
				this.totalSquare = totalSquare

				return temp



			}
		}

	}
};
</script>	

<style lang="scss" scoped>
.content-box {
	width: 100%;

	.content-table {
		width: 96%;
		margin: 0 auto;
		margin-bottom: 1.25rem;
	}

	.head-row {
		margin-top: 1.25rem;
		margin-left: 1.75rem;
		margin-bottom: 1.25rem;

		.el-col {
			margin-left: 1.75rem;
		}
	}

	.upplace {
		padding: 5px 0
	}

	.btnGroup {
		// background-color: aqua;
		display: inline-block;
		// float:right;
		position: absolute;
		top: 75px;
		right: 10px;

	}
}
</style>
